package com.gm.server.voice.utils;


import org.springframework.stereotype.Component;

import javax.sound.sampled.*;
import java.io.*;
import java.net.*;

public class VoiceServer {
    private static final int PORT = 11822;

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("服务器启动，等待客户端连接...");

            Socket socket = serverSocket.accept();
            System.out.println("客户端已连接: " + socket.getInetAddress());

            // 启动接收线程（接收客户端音频并播放）
            new Thread(new ReceiveAudio(socket)).start();
            // 启动发送线程（采集本地音频并发送）
            new Thread(new SendAudio(socket)).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 接收音频并播放
    static class ReceiveAudio implements Runnable {
        private final Socket socket;

        public ReceiveAudio(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                SourceDataLine speaker = AudioUtils.getSpeaker();
                speaker.start();

                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = in.read(buffer)) != -1) {
                    speaker.write(buffer, 0, bytesRead);
                }

                speaker.drain();
                speaker.close();
            } catch (IOException | LineUnavailableException e) {
                e.printStackTrace();
            }
        }
    }

    // 采集音频并发送
    static class SendAudio implements Runnable {
        private final Socket socket;

        public SendAudio(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                OutputStream out = socket.getOutputStream();
                TargetDataLine microphone = AudioUtils.getMicrophone();
                microphone.start();

                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = microphone.read(buffer, 0, buffer.length)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }

                microphone.close();
            } catch (IOException | LineUnavailableException e) {
                e.printStackTrace();
            }
        }
    }
}